#!/bin/bash
#
# 4shared.com module
# Copyright (c) 2010-2012 Plowshare team
#
# This file is part of Plowshare.
#
# Plowshare is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Plowshare is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Plowshare.  If not, see <http://www.gnu.org/licenses/>.

MODULE_BESTREAMS_NET_REGEXP_URL="http://\(\.\)\?bestreams\.net/*/"

MODULE_BESTREAMS_NET_DOWNLOAD_OPTIONS=""
MODULE_BESTREAMS_NET_DOWNLOAD_RESUME=yes
MODULE_BESTREAMS_NET_DOWNLOAD_FINAL_LINK_NEEDS_COOKIE=yes

MODULE_BESTREAMS_NET_LIST_OPTIONS=""

bestreams_net_download() {

local COOKIEFILE=$1
local URL=$2

	Pageinit=$(curl "$URL") || return
#	echo "$Pageinit" > page
  values=$(echo "$Pageinit" | grep 'value="')
#  echo "$values" > values
  op=$(echo "$values" | parse_form_input_by_name 'op')
  id=$(echo "$values" | parse_form_input_by_name 'id')
  fname=$(echo "$values" | parse_form_input_by_name 'fname')
  hash=$(echo "$values" | parse_form_input_by_name 'hash')

# sleep 10

	downloadbtnpage=$(curl -c $COOKIEFILE -e $URL -d "op=$op&usr_login=&id=$id&fname=$fname&referer=$URL&hash=$hash&imhuman=Proceed+to+video" $URL) || return
#	echo 'curl -b $COOKIEFILE -e $URL -d "op=$op&usr_login=&id=$id&fname=$fname&referer=$URL&hash=$hash&imhuman=Proceed+to+video"' > fulllink
	
	# echo "$downloadbtnpage" > downloadbtnpage
	 
	 FILE_URL=$(echo "$downloadbtnpage" | grep 'file:' )
	FILE_URL=${FILE_URL%\"*}
	FILE_URL=${FILE_URL#*\"}
	
	
	if match 'reached the download' "$LINK_HEADER"; then
        # We'll take it literally and wait till the next day
        # Note: Consider the time zone of their server (+4:00)
        local HOUR MIN TIME

        # Get current UTC time, prevent leading zeros
        TIME=$(date -u +'%k:%M') || return
        HOUR=${TIME%:*}
        MIN=${TIME#*:}

        log_error 'Daily limit reached.'
        echo $(( ((23 - ((HOUR + 4) % 24) ) * 60 + (61 - ${MIN#0}) ) * 60 ))
        return $ERR_LINK_TEMP_UNAVAILABLE
    fi
  
	FILENAME="$fname"
	
	echo "$FILE_URL"
	echo "$FILENAME"
}
